﻿using UnityEngine;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace Hont.UMotionGraph
{
    public class LineRendererHub
    {
        class LineRendererPairMeta : Pair
        {
            public LineRenderer LineRenderer;
        }

        public class Pair
        {
            public Transform A;
            public Transform B;
        }

        bool mUseSharedMaterial;
        float mLineRendererWidth;
        Material mMaterial;

        LineRenderer mLineRenderer;
        GameObject mLineRendererHost;
        GameObject mHost;
        List<LineRendererPairMeta> mLineRendererPairList;

        public bool UseSharedMaterial { get { return mUseSharedMaterial; } set { mUseSharedMaterial = value; } }
        public float LineRendererWidth { get { return mLineRendererWidth; } set { mLineRendererWidth = value; } }
        public Material Material { get { return mMaterial; } set { mMaterial = value; } }


        public LineRendererHub()
        {
            mLineRendererWidth = 0.01f;
        }

        public void Init(GameObject host, Pair[] lineRendererPair)
        {
            mHost = host;

            mLineRendererHost = new GameObject("LineRendererHub");
            mLineRendererHost.transform.parent = mHost.transform;
            mLineRendererPairList = new List<LineRendererPairMeta>();

            for (int i = 0; i < lineRendererPair.Length; i++)
            {
                var item = lineRendererPair[i];

                var subLineRenderer = new GameObject("SubLineRenderer");
                subLineRenderer.transform.parent = mLineRendererHost.transform;
                var lineRenderer = subLineRenderer.AddComponent<LineRenderer>();
                lineRenderer.material = mMaterial;
                lineRenderer.SetWidth(mLineRendererWidth, mLineRendererWidth);
                mLineRendererPairList.Add(new LineRendererPairMeta() { A = item.A, B = item.B, LineRenderer = lineRenderer });
            }
        }

        public void Update()
        {
            for (int i = 0; i < mLineRendererPairList.Count; i++)
            {
                var item = mLineRendererPairList[i];

                item.LineRenderer.SetPosition(0, item.A.position);
                item.LineRenderer.SetPosition(1, item.B.position);
            }
        }
    }
}
